package com.xufx.thread.liaoxuefeng.thread9_reentranrLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by xufx on 2022/1/4 12:49
 * synchronized比较重
 * synchronized和reentrantLock都是可重入锁
 * 和synchronized不同的是，ReentrantLock可以尝试获取锁
 * 总结：使用ReentrantLock比使用synchronized更加安全，尝试加锁失败的时候不会导致线程死锁
 */
public class Main {
    private final Lock lock = new ReentrantLock();
    private int count;
    private void add(int i) throws InterruptedException {
        if (lock.tryLock(1, TimeUnit.SECONDS)){
            try {
                // do something
            }finally {
                lock.unlock();
            }
        }
    }
}


